package com.example.excise06.config;

import com.example.excise06.security.UserTokenFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Resource
    private UserTokenFilter userTokenFilter;

    @Bean
    public PasswordEncoder passwordEncoder() {
        // 指定密码加密模式：加盐哈希算法
        return new BCryptPasswordEncoder();
    }

    // 将登录模式设置为无状态模式，关闭跨站脚本攻击功能.配置api访问权限
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                //设置无状态的会话

                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                //无状态请求模式下，不需要拦截跨域脚本攻击
                .and().csrf().disable()// 关闭跨域脚本攻击
                .authorizeRequests() // 开放登录接口
                .antMatchers("/api/**", "/api/login").permitAll()
                .antMatchers("/api/account").authenticated()
                .and()
                //将自定义过滤器添加到登录验证之前
                .addFilterBefore(userTokenFilter, UsernamePasswordAuthenticationFilter.class);;
    }
}